package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"

	"192.168.1.75/go-pkg/errorx"
)

type GoodsSetting struct{}

// Exists 商品配置是否存在
func (GoodsSetting) Exists(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	goodsID string,
	goodsClass string,
) bool {
	gs := query.GoodsSetting
	tx := gs.WithContext(ctx)
	if robotID != "" {
		tx = tx.Where(gs.RobotID.Eq(robotID))
	}
	if goodsID != "" {
		tx = tx.Where(gs.GoodsID.Eq(goodsID))
	}
	if goodsClass != "" {
		tx = tx.Where(gs.GoodsClass.FindInSetWith(goodsClass))
	}
	count, _ := tx.Count()
	return count > 0
}

// Create 新增商品配置
func (GoodsSetting) Create(
	ctx context.Context,
	query *dal.Query,
	goodsID string,
	robotID string,
	goodsType int,
) {
	gs := query.GoodsSetting
	gs.WithContext(ctx).Create(&models.GoodsSetting{
		GoodsID: goodsID,
		RobotID: robotID,
	})
}

func (GoodsSetting) Update(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	goodsID string,
	goodsName string,
	pickupType string, // 取货方式
	goodsTag string, // 商品标签
	cornerLabel string, // 商品脚标
	goodsClass string, // 展示分类
	visible int, // 是否在小程序展示
) error {
	if visible == 0 {
		visible = 1
	}
	gs := query.GoodsSetting
	res, _ := gs.WithContext(ctx).
		Where(gs.RobotID.Eq(robotID)).
		Where(gs.GoodsID.Eq(goodsID)).
		UpdateSimple(
			gs.PickupType.Value(pickupType),
			gs.Tag.Value(goodsTag),
			gs.CornerLabel.Value(cornerLabel),
			gs.GoodsClass.Value(goodsClass),
			gs.Visible.Value(visible),
		)
	if res.RowsAffected <= 0 {
		return errorx.New("更新失败", -1)
	}
	return nil
}

// List 获取商品设置
func (GoodsSetting) List(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	goodsID []string,
	goodsClass string,
	visible int,
	page, limit int,
) (list []*models.GoodsSetting, total int64, err error) {
	gs := query.GoodsSetting
	tx := gs.WithContext(ctx).Where(gs.RobotID.Eq(robotID))
	if len(goodsID) > 0 {
		tx = tx.Where(gs.GoodsID.In(goodsID...))
	}
	if goodsClass != "" {
		tx = tx.Where(gs.GoodsClass.FindInSetWith(goodsClass))
	}
	if visible > 0 {
		tx = tx.Where(gs.Visible.Eq(visible))
	}
	total, _ = tx.Count()
	list, _ = tx.Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Order(gs.GoodsID.Desc()).
		Find()
	return list, total, nil
}
